package xunmeng.web.filter;

import xunmeng.domain.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//@WebFilter("/*")
public class loginfilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //将servletRequest强转化为HttpServletRequest便于获取虚拟目录路径
        HttpServletRequest httpServlet =(HttpServletRequest) servletRequest;
        //获取请求资源
        String path=httpServlet.getRequestURI();
//        System.out.println(path);
        //判断该是否包含登录相关资源路径
        if(path.contains("/login.jsp")||path.contains("/loginservlet")||path.contains("/checkcodeservlet")||path.contains("/css/")||path.contains("/fonts")||path.contains("/js/")){
            //用户想登陆放行
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            //不包含，需要判断该用户是否登录
            if(httpServlet.getSession().getAttribute("admin")==null){
                //没有登录请重新登录，转化到login.jsp页面
                httpServlet.setAttribute("error","您还没有登录，请登录！");
                httpServlet.getRequestDispatcher("/login.jsp").forward(servletRequest, servletResponse);
            }else {
                filterChain.doFilter(servletRequest, servletResponse);
            }
        }

    }

    @Override
    public void destroy() {

    }
}
